<template>
  <view class="content">
    <view class="header">
      上传聊天截图, 获取分析和建议
    </view>
    <view class="info">
      <p>可用次数: {{ availableTimes }}</p>
    </view>
    <u-upload
      :fileList="fileList1"
      @afterRead="afterRead"
      @delete="deletePic"
      name="1"
      multiple
      :maxCount="4"
      height="300"
      width="300"
      :deletable="true"
	  :capture="'album'"
	  uploadText="最多可上传4张聊天记录"
    ><image src="https://bdw-sh-1259268558.cos.ap-shanghai.myqcloud.com/liaotian3.png" 
	mode="widthFix" style="width: 250px;height: 150px;"></image></u-upload>
    <view class="button-row">
      <button class="analyze-button" @click="analyze">获取分析</button>
      <button class="recharge-button" @click="show = true">充值次数</button>
    </view>
	<u-button class="" type="error" @click="gaoji"><u-icon name="level" color="yellow" label-color="yellow" label="体验高级版本"></u-icon></u-button>
	<view class="tip" style="margin-top: 45rpx">
		AI大模型已用百万张聊天数据进行训练, 保证分析结果质量
	</view>
	<view class="tip">
		分析完毕即将聊天截图摧毁, 保证用户隐私
	</view>
    <view v-if="showOverlay" class="overlay">
      <view class="dialog">
        <zero-markdown-view :markdown="analysisResult" class="markdown-content"></zero-markdown-view>
        <button class="close-button" @click="closeOverlay">关闭</button>
      </view>
    </view>

    <view v-if="loading" class="loading-overlay">
      <view class="loading-spinner"></view>
      <p class="loading-text">分析中...{{ countdown }}</p>
    </view>
	
	<u-modal :show="show" :title="title" :content='content' :showCancelButton="true" @confirm="rechargeMembership" @cancel="cancel"></u-modal>
  </view>
</template>

<script>
  import COS from 'cos-js-sdk-v5';

  export default {
    data() {
      return {
        title: '充值提醒',
		content: '20元120张聊天记录图分析, 每次最多可以传入4张照片',
        fileList1: [],
        availableTimes: 0, // 可用次数
        membershipExpiry: "", // 会员到期时间
        showOverlay: false, // 控制浮层显示
        analysisResult: "", // 分析结果
        loading: false, // 控制加载提示
		orderNo: "",
		show: false,
		countdown: 60
      };
    },
    onLoad() {
      this.handleWeChatCallback();
    },
    methods: {
      checkOpenID() {
        const openid = localStorage.getItem('openid');
        console.log(openid);
        if (openid) {
          this.getAvailableTimes(openid); // 获取可用次数和会员到期时间
        } else {
          this.weChatLogin();
        }
      },
	  gaoji() {
		  uni.navigateTo({
		    url: '/pages/index/list'// target为目标页面的路径
		  });
	  },
      weChatLogin() {
        const appId = 'wxad67b499443b7a4b';
        const redirectUri = encodeURIComponent(window.location.href);
        const weChatAuthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base#wechat_redirect`;
        window.location.href = weChatAuthUrl;
      },
      async getAvailableTimes(openid) {
        try {
          const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getUserInfo?open_id=${openid}`);
          const data = await response.json();
          this.availableTimes = data.data.point;
          console.log('可用次数:', this.availableTimes);
          console.log('会员到期时间:', this.membershipExpiry);
        } catch (error) {
          console.error('请求可用次数和会员到期时间时出错:', error);
        }
      },
      deletePic(event) {
        this[`fileList${event.name}`].splice(event.index, 1);
      },
      async afterRead(event) {
        let lists = [].concat(event.file);
        let fileListLen = this[`fileList${event.name}`].length;
        lists.map((item) => {
          this[`fileList${event.name}`].push({
            ...item,
            status: 'uploading',
            message: '上传中',
          });
        });
        for (let i = 0; i < lists.length; i++) {
          const result = await this.uploadFilePromise(lists[i]);
          let item = this[`fileList${event.name}`][fileListLen];
          this[`fileList${event.name}`].splice(
            fileListLen,
            1,
            Object.assign(item, {
              status: 'success',
              message: '',
              url: result,
            })
          );
          fileListLen++;
        }
      },
      uploadFilePromise(file) {
        return new Promise((resolve, reject) => {
          const fileKey = `aaa/${file.name}`;
          const cos = new COS({
            SecretId: 'AKIDhK6oW96L8mJbKvreiZCpXIw6h973lBKH',
            SecretKey: 'rWzJROAlA5mNsBJH2auyxqYi2EAvYYMw',
          });
          this.urlToFile(file.url, file.name, file.type)
            .then((file1) => {
              cos.putObject(
                {
                  Bucket: 'jianji-1259268558',
                  Region: 'ap-shanghai',
                  Key: fileKey,
                  Body: file1,
                  onProgress: function (progressData) {
                    console.log(JSON.stringify(progressData));
                  },
                },
                (err, data) => {
                  if (err) {
                    console.error('上传失败: ', err);
                    reject(err);
                  } else {
                    console.log('上传成功: ', data.Location);
                    resolve("https://" + data.Location);
                  }
                }
              );
            })
            .catch((error) => {
              console.error('转换文件失败: ', error);
              reject(error);
            });
        });
      },
      urlToFile(url, filename, mimeType) {
        return new Promise((resolve, reject) => {
          const xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'blob';
          xhr.onload = function () {
            if (xhr.status === 200) {
              const blob = xhr.response;
              const file = new Blob([blob], { type: mimeType });
              resolve(new File([file], filename, { type: mimeType }));
            } else {
              reject(new Error('Failed to fetch the file'));
            }
          };
          xhr.onerror = function () {
            reject(new Error('Network error'));
          };
          xhr.send();
        });
      },
      async analyze() {
		if (this.fileList1.length == 0) {
			this.analysisResult = "请先上传图片";
			this.showOverlay = true;
			return;
		}
        // 显示加载提示
        this.loading = true;
		this.countdown = 60;
		const interval = setInterval(() => {
			if (this.countdown > 0) {
			  this.countdown--;
			} else {
			  clearInterval(interval);
			}
		}, 1000); // 每秒更新一次
        
        // 假设你有一个 API 可以处理分析请求
        try {
          const response = await fetch('https://data.bingdou.site/server/oneyuan/index/analysisI', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              open_id: localStorage.getItem('openid'),
              image: this.fileList1.map(file => file.url)
            })
          });
          const data = await response.json();
		  if (data.code != 0) {
			  this.analysisResult = data.msg;
		  } else {
			  this.analysisResult = data.data || '分析结果获取失败';
		  }
          console.log('分析结果:', this.analysisResult);
        } catch (error) {
          console.error('获取分析结果时出错:', error);
          this.analysisResult = '获取分析结果时出错';
        } finally {
          // 隐藏加载提示
          this.loading = false;
          // 显示浮层
          this.showOverlay = true;
        }
      },
      closeOverlay() {
        // 关闭浮层
        this.showOverlay = false;
		this.checkOpenID();
      },
      saveOpenID(openid) {
        localStorage.setItem('openid', openid);
      },
      async handleWeChatCallback() {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        if (code) {
          try {
            const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/login?code=${code}`);
            const data = await response.json();
            console.log(data.data.open_id);
            if (data.data.open_id) {
              this.saveOpenID(data.data.open_id);
              this.getAvailableTimes(data.data.open_id); // 获取可用次数和会员到期时间
              window.history.replaceState({}, document.title, window.location.pathname);
            } else {
              console.error('Failed to get openid from server');
            }
          } catch (error) {
            console.error('Error during WeChat login:', error);
          }
        } else {
          this.checkOpenID();
        }
      },
      async rechargeMembership() {
        // 请求服务端获取微信支付参数
        try {
          const response = await fetch('https://data.bingdou.site/server/oneyuan/index/pay', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              open_id: localStorage.getItem('openid')
            })
          });
          const data = await response.json();
		  this.orderNo = data.data.order_no;
		  
		  if (typeof WeixinJSBridge == "undefined") {
		      if (document.addEventListener) {
		          document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
		      } else if (document.attachEvent) {
		          document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
		          document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
		      }
		  } else {
		      this.onBridgeReady(data);
		  }
		} catch (error) {
		  console.error('请求支付参数时出错:', error);
		}
      },
	  
	  onBridgeReady(data) {
		  var that = this
		  WeixinJSBridge.invoke('getBrandWCPayRequest', {
		      "appId": data.data.appId,     //公众号ID，由商户传入     
		      "timeStamp": data.data.timeStamp,     //时间戳，自1970年以来的秒数     
		      "nonceStr": data.data.nonceStr,      //随机串     
		      "package": data.data.package,
		      "signType": "MD5",     //微信签名方式：     
		      "paySign": data.data.paySign,
		  },
		  function(res) {
		      if (res.err_msg == "get_brand_wcpay_request:ok") {
		          // 使用以上方式判断前端返回,微信团队郑重提示：
		          //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
		  		  that.pollPaymentResult();
		      }
		  });
	  },
	  cancel() {
		  this.show = false;
	  },
	  async pollPaymentResult() {
        const pollInterval = 1000; // 轮询间隔时间（毫秒）
        const maxAttempts = 20; // 最大轮询次数
        let attempts = 0;
		const orderNo = this.orderNo;
        const poll = async () => {
          try {
            const response = await fetch(`https://data.bingdou.site/server/oneyuan/index/getOrderPayment?order_no=${orderNo}`);
            const data = await response.json();
            if (data.code === 0) {
              // 支付成功
              // alert('充值成功');
              this.getAvailableTimes(localStorage.getItem('openid')); // 更新会员信息
              return;
            } else if (data.code === 1) {
              // 支付进行中，继续轮询
              if (attempts < maxAttempts) {
                attempts++;
                setTimeout(poll, pollInterval);
              } else {
                alert('支付结果查询超时');
              }
            } else {
              // 支付失败
              alert('支付失败');
            }
          } catch (error) {
            console.error('查询支付结果时出错:', error);
            alert('查询支付结果时出错');
          }
        };

        poll();
      }
    }
  };
</script>

<style>
  html, body, .content {
    height: 100%;
    margin: 0;
    padding: 0;
  }
  
  .tip {
	  font-size: 25rpx;
  }

  .content {
	margin-top: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 20px;
  }

  .header {
    font-size: 18px;
    color: #333;
    margin-bottom: 20px;
    text-align: center;
	font-weight: 800;
  }

  .info {
    font-size: 16px;
    color: #555;
    margin-bottom: 20px;
    text-align: center;
  }

  .upload-button {
    /* border: 2px dashed #007bff; */
    /* border-radius: 8px; */
    /* padding: 13px; */
    /* background-color: #e9f7fe; */
    color: #007bff;
    font-size: 22px;
    cursor: pointer;
    transition: background-color 0.3s, color 0.3s;
  }

  /* .upload-button:hover { */
    /* background-color: #007bff; */
    /* color: white; */
  /* } */

  .preview-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    width: 100%;
    max-width: 500px; /* 限制预览区域的最大宽度 */
  }

  .preview-item {
    position: relative;
    width: calc(50% - 30px); /* 每个预览项占50%的宽度，并减去一些间距 */
    margin-bottom: 10px;
    border: 1px solid #ddd;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .preview-image {
    width: 80%;
    height: auto;
    object-fit: cover;
  }

  .delete-button {
    position: absolute;
    top: 5px;
    right: 5px;
    background-color: rgba(255, 255, 255, 0.8);
    border: none;
    border-radius: 50%;
    padding: 5px;
    cursor: pointer;
  }

  .button-row {
    display: flex;
    justify-content: center;
    gap: 10px; /* 按钮之间的间距 */
	margin-top: 20px;
    margin-bottom: 40px; /* 添加底部间距 */
    width: 100%; /* 确保按钮行的宽度 */
    max-width: 500px; /* 限制按钮行的最大宽度 */
  }

  .analyze-button {
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 15px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .analyze-button:hover {
	padding: 10px 15px;
    background-color: #0056b3;
  }

  .recharge-button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .recharge-button:hover {
    background-color: #218838;
  }
  
  .u-upload__deletable {
    z-index: 999;
  }

  .overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8); /* 设置为不透明 */
    display: flex;
    align-items: center;
    justify-content: center;
	z-index: 1000;
  }

  .dialog {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    text-align: center;
    max-height: 80vh; /* 限制对话框的最大高度 */
    overflow: auto; /* 添加滚动 */
  }

  .markdown-content {
    max-height: 60vh; /* 限制markdown内容的最大高度 */
    overflow: auto; /* 添加滚动 */
    text-align: left;
  }

  .close-button {
    margin-top: 20px;
    background-color: #007bff;
    color: white;
    border: none;
    padding: 10px 20px;
    font-size: 16px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s;
  }

  .close-button:hover {
    background-color: #0056b3;
  }

  .loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.8); /* 覆盖整个页面 */
    display: flex;
    flex-direction: column; /* 使文字和加载图标垂直排列 */
    align-items: center;
    justify-content: center;
    z-index: 1000; /* 确保加载提示在最上层 */
  }

  .loading-spinner {
    border: 8px solid #f3f3f3; /* Light grey */
    border-top: 8px solid #007bff; /* Blue */
    border-radius: 50%;
    width: 60px;
    height: 60px;
    animation: spin 1s linear infinite;
  }

  .loading-text {
    margin-top: 20px;
    color: white;
    font-size: 18px;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
</style>
